package com.fatcat.easybuy.controller;

import com.fatcat.easybuy.annotaion.CheckPermission;
import com.fatcat.easybuy.pojo.EasyBuyProductCategory;
import com.fatcat.easybuy.service.EasyBuyProductCategoryService;
import com.fatcat.easybuy.service.EasyBuyProductService;
import com.fatcat.easybuy.util.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


/**
 * @author 李开辰
 * @since 2025/9/13 14:39
 */
@Api(tags = "分类模块")
@CheckPermission("0")
@RestController
@RequestMapping("/category")
public class EasyBuyProductCategoryController {
    @Autowired
    private EasyBuyProductCategoryService easyBuyProductCategoryService;
    @Autowired
    private EasyBuyProductService easyBuyProductService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/getCategoryTree")
    public ResponseResult getTree() {
        return ResponseResult.success("查询成功").add("categoryTree", easyBuyProductCategoryService.getCategoryTree());
    }

    @PostMapping("/addCategory")
    public ResponseResult addCategory(@RequestBody EasyBuyProductCategory easyBuyProductCategory) {
        if (easyBuyProductCategoryService.addCategory(easyBuyProductCategory)) {
            return ResponseResult.success().add("data", "添加成功");
        } else {
            return ResponseResult.error().add("data", "添加失败,该分类下存在相同名字的分类");
        }

    }

    @Transactional  // 保证原子性
    @PostMapping("/updateCategory")
    public ResponseResult updateCategory(
            @RequestBody EasyBuyProductCategory category,
            @RequestParam Long level1Id,
            @RequestParam Long level2Id,
            @RequestParam Long level3Id
    ) {
        // 1. 先更新分类表
        boolean isCategoryUpdated = easyBuyProductCategoryService.updateCategory(category);
        if (!isCategoryUpdated) {
            return ResponseResult.error("分类更新失败");
        }

        // 2. 再更新商品表
        boolean isProductUpdated = easyBuyProductCategoryService.updateProductLevel(
                level1Id, level2Id, level3Id, category
        );

        return isProductUpdated ?
                ResponseResult.success("更新成功") :
                ResponseResult.error("商品层级更新失败");
    }

    @DeleteMapping("/deleteCategory/{id}&{type}")
    public ResponseResult deleteCategory(@PathVariable("id") Long id,
                                         @PathVariable("type") Integer type){
//        String storedToken = stringRedisTemplate.opsForValue().get(id.toString());
//        if (!token.equals(storedToken)) {
//            stringRedisTemplate.delete(id.toString());
//            return ResponseResult.error("操作令牌无效或已过期");
//        }
//        stringRedisTemplate.delete(id.toString());

        // 根据分类类型检查是否存在关联产品
        boolean hasProducts = false;
        String errorMessage = "";

        switch (type) {
            case 1:
                hasProducts = easyBuyProductService.checkExitProductOfLevel1(id);
                errorMessage = "该一级分类下存在产品，无法删除";
                break;
            case 2:
                hasProducts = easyBuyProductService.checkExitProductOfLevel2(id);
                errorMessage = "该二级分类下存在产品，无法删除";
                break;
            case 3:
                hasProducts = easyBuyProductService.checkExitProductOfLevel3(id);
                errorMessage = "该三级分类下存在产品，无法删除";
                break;
            default:
                return ResponseResult.error().add("data", "无效的分类类型");
        }

        // 如果存在关联产品，返回错误信息
        if (hasProducts) {
            return ResponseResult.error("505",errorMessage);
        }
        // 执行删除操作
        if (easyBuyProductCategoryService.deleteCategory(id)) {
            return ResponseResult.success().add("data", "删除成功");
        } else {
            return ResponseResult.error().add("data", "删除失败");
        }

    }

//    @GetMapping("/getCategoryToken/{id}")
//    public ResponseResult getCategoryToken(@PathVariable("id") Long id){
//        String DataTime= String.valueOf(System.currentTimeMillis());
//        String Token= Sm3Util.hmacEncrypt(DataTime);
//        stringRedisTemplate.opsForValue().set(
//                id.toString(),
//                Token,
//                5, TimeUnit.MINUTES // 添加5分钟过期
//        );
//        return ResponseResult.success().add("token",Token);
//    }

    @GetMapping("/getCategoryLevel1Id")
    public ResponseResult getCategoryLevel1Id() {
        return ResponseResult.success("查询成功").add("categoryList", easyBuyProductCategoryService.getLevel1Categories());
    }

    @GetMapping("/getCategoryParent/{parentId}")
    public ResponseResult getCategoryParent(@PathVariable("parentId") Long parentId) {
        return ResponseResult.success("查询成功").add("categoryList", easyBuyProductCategoryService.getCategoriesByParentId(parentId));
    }



}
